<?php
namespace Hdphim\Library\Controllers;

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Dispatcher;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BackendController
 *
 * @author root
 */
class BackendController extends Controller
{
     /**
     * Execute before the router so we can determine if this is a provate controller, and must be authenticated, or a
     * public controller that is open to all.
     *
     * @param Dispatcher $dispatcher
     * @return boolean
     */
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        $identity = $this->auth->getIdentity();
        if(!is_array($identity) || $identity['group'] == 'user')
        {
            $this->response->redirect();
        }
        
        $moduleName = $dispatcher->getModuleName();
        
        $controllerName = $dispatcher->getControllerName();      
       
        // Only check permissions on private controllers
        if ($this->acl->isPrivate($controllerName)) {           
            // Get the current identity            
            
            if(!is_array($identity))
            {
                $this->flash->notice('You don\'t have access to this module: private');

                $dispatcher->forward(array(
                    'controller' => 'index',
                    'action' => 'index'
                ));
                return false;
            }
            
            // Check if the user have permission to the current option
            $actionName = $dispatcher->getActionName();
            
            if(!$this->acl->isAllowed($identity['group'] , $controllerName , $actionName))
            {
                 $this->flash->notice('You don\'t have access to this module: ' . $controllerName . ':' . $actionName);
                 return false;
            }
        }
    }
}
